<?php

/**
 * Description of Utils
 * 
 * @author anhducbkhn
 * @since Sep 5, 2013 - 3:30:29 PM
 */
class Utils
{

    const MONDAY    = 'Monday';
    const TUESDAY   = 'Tuesday';
    const WEDNESDAY = 'Wednesday';
    const THURSDAY  = 'Thursday';
    const FRIDAY    = 'Friday';
    const SATURDAY  = 'Saturday';
    const SUNDAY    = 'Sunday';
    //day of day
    const MORNING   = 'Morning';
    const AFTERNOON = 'Afternoon';
    const EVENING   = 'Evening';
    const PAYPAL_   = '';

    /**
     * 
     * @param mixed $array_config array(
     *          'cmd'=>'_cart',
     *          'business'=>'seller@designerfotos.com',
     *          'item_name'=>'hat',
     *          'item_number'=>'123',
     *          'amount'=>'15.00',
     *          'first_name'=>'John',
     *          'last_name'=>'Doe',
     *          'address1'=>'hat',
     *          'address2'=>'hat',
     *          'city'=>'hat',
     *          'state'=>'hat',
     *          'zip'=>'hat',
     *      
     * @link https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/formbasics/ description
     * @return string
     * LIVE SITE: https://www.paypal.com/cgi-bin/webscr
     */
    public static function gen_paypal_button($array_config, $url_button = 'https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif')
    {
        $url_button = Yii::app()->baseURL . '/themes/webmaster/assets/img/express-checkout.png';
        $html       = '<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">';
        foreach ($array_config as $key => $value)
        {
            $html.='<input type="hidden" name="' . $key . '" value="' . $value . '" >';
        }
        $html.='<input type="image" name="submit" border="0" src="' . $url_button . '" alt="PayPal - The safer, easier way to pay online">';
        $html.='</form>';

        return $html;
    }

    /**
     * ['mon','tue','web'..'stat']
     */
    public static function getSevenDayAgo()
    {

        $arr = self::_getSevenDayAgo();
        return json_encode($arr);
    }

    public static function getPageview()
    {
        $arr_result = array();

        $arr = self::_getSevenDayAgo(TRUE);
        foreach ($arr as $daytime => $value)
        {
            $visitors     = StatCounter::countVisitorsByDate($daytime);
            $year         = date('Y', $daytime);
            $month        = date('n', $daytime);
            $day          = date('j', $daytime);
            $arr_result[] = array(
                "K($year, $month, $day)",
                $visitors
            );
        }

        return json_encode($arr_result);
    }

    public static function _getSevenDayAgo($getKey = FALSE, $getDay = FALSE)
    {
        $arr_result   = array();
        $current_date = new DateTime('NOW');

        $current_date->sub(new DateInterval("P6D"));
        if ($getDay == TRUE)
        {
            return $current_date->format('d/M');
        }
        elseif ($getKey == FALSE)
        {
            $arr_result[] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[] = $current_date->format('D');
        }
        else
        {
            $arr_result[$current_date->getTimestamp()] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[$current_date->getTimestamp()] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[$current_date->getTimestamp()] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[$current_date->getTimestamp()] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[$current_date->getTimestamp()] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[$current_date->getTimestamp()] = $current_date->format('D');

            $current_date->add(new DateInterval("P1D"));
            $arr_result[$current_date->getTimestamp()] = $current_date->format('D');
        }
        return $arr_result;
    }

    public static function _getRecent30Day($returnText = FALSE)
    {

        $arr_result = array();
        $day_int    = 24 * 3600;
        $today      = strtotime("today");
        //Lấy 6 tuần trước đổ lại
        for ($i = 30; $i > 0; $i--)
        {
            $arr_result[] = $returnText ? date('d-m-Y', $today - $day_int * $i) : $today - $day_int * $i;
        }
        //Thêm ngày hiện tại
        $arr_result[] = $returnText ? date('d-m-Y', strtotime('today')) : strtotime('today');
        return $arr_result;
    }

    /**
     * List day current month, from first day to current day
     * @param type $showInChart return data format for chart if TRUE
     * @return mixed list day
     */
    public static function _getDaysCurrentMonth($showInChart = FALSE)
    {
        $first_day_this_month = strtotime('first day of this month');
        $today                = strtotime("today");
        $day                  = date('d', $today) - date('d', $first_day_this_month);
        $arr_result           = array();
        $day_seconds          = 24 * 3600;
        if ($day > 0)
        {
            for ($i = $day; $i > 0; $i--)
            {
                $step_day     = $today - $day_seconds * $i;
                $arr_result[] = $showInChart ? '"' . date('d/M/Y', $step_day) . '"' : date('d-m-Y', $step_day);
            }
        }
        //Thêm ngày hiện tại
        $arr_result[] = $showInChart ? '"' . date('d/M/Y', $today) . '"' : date('d-m-Y', $today);
        return $showInChart ? self::convertChartData($arr_result) : $arr_result;
    }

    /**
     * Lấy 7 tuần gần nhất
     * @param type $getKey
     * @param type $getDay
     * @return type
     */
    public static function _getRecent7Week()
    {
        $arr_result   = array();
        $week_int     = 7 * 24 * 3600;
        $current_week = strtotime("Monday this week");
        //Lấy 6 tuần trước đổ lại
        for ($i = 6; $i > 0; $i--)
        {
            $arr_result[] = $current_week - $week_int * $i;
        }
        //Thêm tuần hiện tại
        $arr_result[] = $current_week;

        return $arr_result;
    }

    public static function getMoneyByTime($time = 'month')
    {
        if ($time == 'month')
        {
            return self::getMoneyByMonth(true);
        }
        elseif ($time == 'week')
        {

            return self::getMoneyByWeek();
        }
        elseif ($time == 'daily')
        {
            return self::getMoneyByDay();
        }
        else
        {
            return array();
        }
    }

    public static function getMoneyByMonth($chartData = FALSE)
    {
        $arr_result     = array();
        //Cac hoa don duoc thiet lap trong nam
        $receipt        = Receipt::getTotalReceiptThisYear();
        $retail_receipt = Receipt::getTotalRetailReceiptThisYear();
        foreach ($receipt as $item)
        {
            // Tinh tong hoa dong phat sinh trong thang
            $month = date('n', $item->receipt_date);
            if (isset($arr_result[$month]))
            {
                $arr_result[$month] += $item->final_price;
            }
            else
            {
                $arr_result[$month] = $item->final_price;
            }
        }
        foreach ($retail_receipt as $v)
        {
            // Tinh tong hoa dong phat sinh trong thang
            $month = date('n', $v->receipt_date);
            if (isset($arr_result[$month]))
            {
                $arr_result[$month] += $v->final_price;
            }
            else
            {
                $arr_result[$month] = $v->final_price;
            }
        }

        foreach (self::listMonth() as $month)
        {
            if (!array_key_exists($month, $arr_result))
                $arr_result[$month] = 0;
        }
        ksort($arr_result);
        return ($chartData) ? self::convertChartData($arr_result) : $arr_result;
    }

    static function listMonth($showInChart = FALSE)
    {
        $current_month = date('n', time());
        for ($i = 1; $i <= $current_month; $i++)
            $list_month[]  = $showInChart ? '"' . strftime('%b/%G', mktime(0, 0, 0, $i, 1)) . '"' : $i;
        return $showInChart ? self::convertChartData($list_month) : $list_month;
    }

    public static function getMoneyByWeek()
    {
        $arr_result = array();

        //array đầu tuần của 7 tuần vừa qua
        $list_recent_7wk = Utils::_getRecent7Week();

        foreach ($list_recent_7wk as $key => $start_date)
        {
            $money    = 0;
            //array CN của 7 tuần vừa qua
            $end_date = strtotime('next sunday', $start_date);

            //Cac hoa don duoc thiet lap trong 7 tuan qua
            $cri = new CDbCriteria();

            $cri->condition = "(receipt_date BETWEEN '$start_date' AND '$end_date')";
            if (Yii::app()->user->isAdmin())
            {
                
            }
            if (Yii::app()->user->isMerchant())
            {
                $cri->with = array('order', 'order.service', 'order.service.user');
                $cri->compare('user.id', Yii::app()->user->id);
            }
            $receipt = Receipt::model()->findAll($cri);
            //For retail order
            $cri     = new CDbCriteria();

            $cri->condition = "(receipt_date BETWEEN '$start_date' AND '$end_date')";
            if (Yii::app()->user->isAdmin())
            {
                
            }
            if (Yii::app()->user->isMerchant())
            {
                $cri->with = array('order');
                $cri->compare('order.biz_id', Yii::app()->user->id);
            }
            $retail_receipt = RetailReceipt::model()->findAll($cri);

            foreach ($receipt as $item)
            {
                // Tinh tong hoa dong phat sinh trong tuan
                $money += $item->final_price;
            }
            foreach ($retail_receipt as $v)
            {
                // Tinh tong hoa dong phat sinh trong tuan
                $money += $v->final_price;
            }
            $arr_result[] = array($key, $money);
        }

        return json_encode($arr_result);
    }

    public static function getMoneyByDay()
    {
        $arr_result        = array();
        $list_recent_30day = Utils::_getDaysCurrentMonth();
        foreach ($list_recent_30day as $key => $date)
        {
            $money          = 0;
            $cri            = new CDbCriteria();
            $cri->condition = "FROM_UNIXTIME(`receipt_date`, '%d-%m-%Y')=:d";
            $cri->params    = array(':d' => $date);

            if (user()->isMerchant() || user()->isBranch())
            {
                $cri->with = array('order', 'order.service', 'order.service.user');
                $cri->compare('user.id', user()->id);
            }
            $receipt = Receipt::model()->findAll($cri);

            //For retail order
            $cri = new CDbCriteria();

            $cri->condition = "FROM_UNIXTIME(`receipt_date`, '%d-%m-%Y')=:d";
            $cri->params    = array(':d' => $date);
            if (user()->isMerchant() || user()->isBranch())
            {
                $cri->with = array('order');
                $cri->compare('order.biz_id', Yii::app()->user->id);
            }
            $retail_receipt = RetailReceipt::model()->findAll($cri);

            foreach ($receipt as $item)
            {
                // Tinh tong hoa dong phat sinh trong tuan
                $money += $item->final_price;
            }
            foreach ($retail_receipt as $v)
            {
                // Tinh tong hoa dong phat sinh trong tuan
                $money += $v->final_price;
            }
            $arr_result[] = array($key + 1, $money);
        }
        return json_encode($arr_result);
    }

    public static function convertChartData($array)
    {
        $data = '[';
        foreach ($array as $key => $value)
        {
            if ($data != '[')
            {
                $data .= ', ';
            }
            $data .= "[$key, $value]";
        }

        $data .= ']';

        return $data;
    }

    /**
     * @assert ('Saturday, 28 Dec, 2013') == expectedResult
     * @param string  $ip_str_time
     * @return int timestamp
     */
    public static function formatAppointTime($ip_str_time)
    {
        $t = date_create_from_format("D, d M, Y", $ip_str_time);
        $t->setTime(0, 0, 0);
        return $t->getTimestamp();
    }

    /**
     * Genarate a list of spate of time
     */
    public static function genStepList($start_time, $end_time)
    {
        // Kết thúc lúc 19h30
        if ($start_time == NULL)
            $startTime = 0 * 60;

        if ($end_time == NULL)
            $endTime = 23 * 60 + 30;

        $data = array();

        for ($i = $startTime; $i <= $endTime; $i+=15)
        {
            //$data[$i] = $this->convertIntToTime($i);
            $data[$i] = convertIntToTime($i);
        }

        return $data;
    }

    /**
     * set hour=0, min=0, second=0
     * @param string  $str_time time in textual English
     * @return int timestamp
     */
    public static function formatTime($str_time)
    {
        $time     = new DateTime();
        $int_time = strtotime($str_time);

        $time->setTime(0, 0, 0);
        $time->setDate(
                date('Y', $int_time), date('m', $int_time), date('d', $int_time));

        return $time->getTimestamp();
    }

    /**
     * @assert ('14:00','17:35','08:00','17:30','12:00','13:30') == FALSE
     * @assert ('08:00','12:05','08:00','17:30','12:00','13:30') == FALSE
     * @assert ('12:00','13:30','08:00','17:30','12:00','13:30') == FALSE
     * @assert ('08:00','12:00','08:00','17:30','12:00','13:30') == TRUE
     * @assert ('13:30','17:30','08:00','17:30','12:00','13:30') == TRUE
     * @assert ('08:00','09:00','08:00','17:30','12:00','13:30') == TRUE
     * @param type $start_appt_time
     * @param type $end_appt_time
     * @param type $start_time
     * @param type $end_time
     * @param type $start_lunch
     * @param type $end_lunch
     * @return boolean <b>TRUE</b> if validate or <b>FALSE</b> otherwise
     */
    public static function compareWorkTime($start_appt_time, $end_appt_time, $start_time, $end_time, $start_lunch, $end_lunch)
    {

        //check start_time to start_lunch
        if ((strtotime($start_appt_time) >= strtotime($start_time)) &&
                (strtotime($end_appt_time) <= strtotime($start_lunch)))
            return TRUE;

        //check end_lunch to end time
        if ((strtotime($start_appt_time) >= strtotime($end_lunch)) &&
                (strtotime($end_appt_time) <= strtotime($end_time)))
            return TRUE;
        return FALSE;
    }

    /**

     * @assert ('12:00', '11:00') == TRUE;
     * @assert ('12:05', '11:59') == TRUE;
     * @param type $time1
     * @param type $time2
     * @return boolean
     */
    public function genTime($time1, $time2)
    {
        if (strtotime($time1) >= strtotime($time2))
        {
            return TRUE;
        }
        return FALSE;
    }

    /**
     * @assert (420) == '07:00'
     * @assert (540) == '09:00'
     * @assert (585) == '09:45'
     * @assert (1140) == '19:00'
     * @assert (1170) == '19:30'
     * @param type $seconds
     * @return type
     */
    function minutesToTime($seconds)
    {

        // extract hours
        $hours = floor($seconds / 60);
        if ($hours < 10)
        {
            $hours = '0' . $hours;
        }
        // extract minutes
        $divisor_for_minutes = $seconds % 60;
        if ($divisor_for_minutes < 10)
        {
            $divisor_for_minutes = '0' . $divisor_for_minutes;
        }

        return $hours . ':' . $divisor_for_minutes;
    }

    /**
     * 
     * @param int number of minutes
     * @return int number of second
     */
    static function minutesToTimeStamp($str_time)
    {
        return $str_time * 60;
    }

    /**
     * 
     * @param int $step minutes on a step
     * @param string $start time start "08:00"
     * @param string  $end time end  "16:00"
     * @param boolean $value <b>TRUE</b> if key is H:i or <b>FALSE</b> if otherwise
     * @return mixed list of time
     */
    static function minuteStep($step = 5, $start = "08:00", $end = "16:00", $value = TRUE)
    {
        if ($start == '' || $start == NULL || $end == '' || $end == NULL)
            return array();

        $start_time = strtotime($start);
        $end_time   = strtotime($end);

        $minute_step = $step * 60;
        $ret         = array();

        for ($i = $start_time; $i <= $end_time; $i+=$minute_step)
        {
            if (!$value)
            {
                $ret[] = date("H:i", $i);
            }
            else
            {

                $ret[date("H:i", $i)] = date("H:ia", $i);
            }
        }
        return $ret;
    }

    /**
     * @VOITHAN: List thời gian lớn hơn thời gian hiện tại
     * @param int $step minutes on a step
     * @param string  $start time end  "16:00"
     * @param string  $end time end  "16:00"
     * @param integer  $open_time khoảng cách thời gian (open_time của merchant)
     * @return mixed list of time
     */
    static function minuteStepExcludePastTime($step = 5, $start = "08:00", $end = "16:00", $open_time = 0, $cover_time_service = 0)
    {
        if ($start == '' || $start == NULL || $end == '' || $end == NULL)
        {
            return array();
        }

        $start_time = strtotime($start);
        $end_time   = strtotime($end);



        $minute_step = $step * 60;

        $crr = date("H:i", time());

        $crr_time       = strtotime($crr) + $open_time + $cover_time_service;
        $crr_time_round = self::roundTime($crr_time);

        $ret = array();

        //thời gian bắt đầu nhỏ hơn (thời gian hiện tại + $open_time)(đã qua)
        if ($crr_time_round >= $start_time)
        {
            for ($i = $crr_time_round; $i <= $end_time; $i+=$minute_step)
            {
                $ret[] = date("H:i", $i);
            }
        }
        else
        {
            for ($i = $start_time; $i <= $end_time; $i+=$minute_step)
            {
                $ret[] = date("H:i", $i);
            }
        }
        return $ret;
    }

    /**
     * 
     * @param int $leng length of string return
     * @return string radom string
     */
    public static function genRandomString($leng = 10)
    {
        return substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 5)), 0, $leng);
    }

    public static function convertUrlString($ip_str)
    {
        return str_replace(' ', '+', $ip_str);
    }

    /**
     * Calculates the great-circle distance between two points, with
     * the Haversine formula.
     * @param float $latitudeFrom Latitude of start point in [deg decimal]
     * @param float $longitudeFrom Longitude of start point in [deg decimal]
     * @param float $latitudeTo Latitude of target point in [deg decimal]
     * @param float $longitudeTo Longitude of target point in [deg decimal]
     * @param float $earthRadius Mean earth radius in [m]
     * @return float Distance between points in [m] (same as earthRadius)
     */
    public static function haversineGreatCircleDistance(
    $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
    {
        // convert from degrees to radians
        $latFrom = deg2rad($latitudeFrom);
        $lonFrom = deg2rad($longitudeFrom);
        $latTo   = deg2rad($latitudeTo);
        $lonTo   = deg2rad($longitudeTo);

        $latDelta = $latTo - $latFrom;
        $lonDelta = $lonTo - $lonFrom;

        $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
                                cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
        return $angle * $earthRadius;
    }

    //round number 5 to 10, 17 to 20
    public static function roundrecover($num)
    {
        $separatedData = explode('.', (string) ($num / 10));
        $odd           = ($num / 10) - $separatedData[0];
        $ret           = ($separatedData[0] + ceil($odd)) * 10;
        return $ret;
    }

    //round time integer 420 to 600(7 min to 10min)
    public static function roundTime($TimeInt)
    {
        return (60 * 5) * ceil($TimeInt / (60 * 5));
    }

    /**
     * 
     * @param int $point
     * @param int $total
     * @param int $sid
     */
    public static function getContentVote($point, $total, $sid)
    {
        $count_time = 0;
        while ($point >= 1 && $count_time <= $total)
        {
            echo '<i class="webmaster-icon webmaster-icon-voted" onclick="vote($(this),' . $sid . ',' . ($count_time + 1) . ')"></i>';
            $point-=1;
            $count_time+=1;
        }

        if ($point > 0)
        {
            echo '<i class="webmaster-icon webmaster-icon-half" onclick="vote($(this),' . $sid . ',' . ($count_time + 1) . ')"></i>';
            $count_time+=1;
        }

        while ($count_time < 5)
        {
            echo '<i class="webmaster-icon webmaster-icon-unvote" onclick="vote($(this),' . $sid . ',' . ($count_time + 1) . ')"></i>';
            $count_time+=1;
        }
        echo '<br />';
        echo '<span class="vote-count">(' . ServiceRate::getReviewTimes($sid) . ' ratings)</span>';
    }

    public static function convertToStamp($start_time, $datestamp)
    {
        $date = strtotime($start_time . date('Y-m-d', $datestamp));
//        $result = date("Y-m-d G:i", $date);
        return $date;
    }

    public static function plusminute($ip_time, $param_duration = 0, $param_recovery = 0)
    {
        $currentDate = strtotime($ip_time);
        $futureDate  = $currentDate + (60 * $param_duration);
        return ltrim(date("H:i", $futureDate), '0');
    }

    /**
     * reset time stamp to 00:00:00
     * @param int $time timeStamp
     * @return int timestamp with format 00:00:00
     */
    public static function getResetTimeStamp($time)
    {
        $time_obj = new DateTime();
        $time_obj->setTimestamp($time);
        $time_obj->setTime(0, 0, 0);

        return $time_obj->getTimestamp();
    }

    /**
     * Tạo link bitly
     * @param type $url
     * @return string bitly short link
     */
    public static function getBitlyUrl($url)
    {
        $bitly  = Yii::app()->bitly->shorten($url)->getResponseData();
        $encode = json_decode($bitly);

        //if ok
        if ($encode->status_code == 200)
        {
            return $encode->data->url;
        }
        else
        {
            return $url;
        }
    }

    /**
     * Convert second to days, hours, mins
     * @param int $second
     * @param boolean $withDay TRUE: tính lẻ giờ, FALSE: tính tổng cộng giờ
     * @return mixed 
     */
    public static function convertSecondToTime($second, $withDay = TRUE)
    {
        $time          = array();
        $time['days']  = floor($second / 86400);
        $time['hours'] = $withDay == TRUE ? floor(($second % 86400) / 3600) : floor($second / 3600);
        $time['mins']  = floor(($second % 3600) / 60);

        return $time;
    }

    /**
     * 
     */
    public static function splitString($ip_time)
    {
        $ar_temp = explode("-", $ip_time);

        $arr_result[] = trim($ar_temp[0]);
        $arr_result[] = trim($ar_temp[1]);

        return $arr_result;
    }

    public static function formatNumber($number)
    {
        return number_format($number, 0, ',', ' ');
        ;
    }

    //explode by multi delimiter
    public static function multiexplode($delimiters, $string)
    {
        $ready  = str_replace($delimiters, $delimiters[0], $string);
        $launch = explode($delimiters[0], $ready);
        return $launch;
    }

    public static function convertTimeToInt($time, $meridian = FALSE)
    {
        if (!$meridian)
        {
            $arr = explode(":", $time);
            if (count($arr) == 2)
            {
                return intval($arr[0]) * 60 + intval($arr[1]);
            }
        }
        else
        {
            $true_time = date("H:i", strtotime($time)); //08:00 PM => 20:00
            $true_time = $true_time != 0 ? $true_time : '23:59'; //00:00 => '23:59'
            $arr       = explode(":", $true_time);
            if (count($arr) == 2)
            {
                return intval($arr[0]) * 60 + intval($arr[1]);
            }
        }
        return 8 * 60;
    }

    /**
     * Get text time
     * Xác định thời gian đăng bài, ví dụ: 2 hours ago
     * @param int $time 
     * @param int $maxDay quy định số ngày lớn nhất, ví dụ nếu $maxDay=5 thì chỉ
     * lấy texttime trong khoảng 5 ngày đổ lại
     * @return type
     */
    public static function getTextTime($time, $maxDay = 5)
    {
        $maxDaySecond = time() - $maxDay * 24 * 3600;
        if ($time < $maxDaySecond)
        {
            return date('d/M/Y', $time);
        }
        $range = time() - $time;
        $days  = floor($range / 86400);
        $hours = floor(($range % 86400) / 3600);
        $mins  = floor(($range % 3600) / 60);

        if ($days > 0)
            return $days > 1 ? "about $days days ago" : "about $days days ago";
        else
        {
            if ($hours > 0)
                return $hours > 1 ? "about $hours hours ago" : "about $hours hours ago";
            else
            {
                if ($mins > 0)
                    return $mins > 1 ? "about $mins mins ago" : "about $mins min ago";
                else
                {
                    return "about fews seconds ago";
                }
            }
        }
    }

    /**
     * check the facebook link is personal account or fan page
     * @param type $link
     */
    static function isFacebookFanpage($link)
    {
        if ($link == NULL OR $link == '')
            return false;
//        $alias = preg_replace('#(?:https?://)?(?:www.)?(?:facebook.com/)?(?:(?:\w)*\#!/)?(?:pages/)?(?:[?\p{L}\-_]*/)?(?:[?\w\-_]*/)?(?:profile.php\?id=(?=\d.*))?([\d\-]*)?(?:\?.*)?#u', '$1', $link);
        $page     = preg_replace("/^(?:https:\/\/)?(.*)/", "https://$1", $link);
        $graph    = "https://graph.facebook.com/$page"; //Facebook graph api link
        $_content = @file_get_contents($graph);
        $content  = $_content != FALSE ? json_decode($_content) : NULL;
        //only fan page has 'likes'
        return ($content != NULL && isset($content->likes)) ? TRUE : FALSE;
    }

    static function word_limiter($str, $limit = 100, $end_char = '&#8230;')
    {
        if (trim($str) == '')
            return $str;
        preg_match('/^\s*+(?:\S++\s*+){1,' . (int) $limit . '}/', $str, $matches);
        if (strlen($str) == strlen($matches[0]))
            $end_char = '';
        return $matches[0] . $end_char;
    }

    static function utf8_string_to_url($string)
    {
        $trans = array(
            'à'   => 'a', 'á'   => 'a', 'ả'   => 'a', 'ã'   => 'a', 'ạ'   => 'a',
            'ă'   => 'a', 'ằ'   => 'a', 'ắ'   => 'a', 'ẳ'   => 'a', 'ẵ'   => 'a', 'ặ'   => 'a',
            'â'   => 'a', 'ầ'   => 'a', 'ấ'   => 'a', 'ẩ'   => 'a', 'ẫ'   => 'a', 'ậ'   => 'a',
            'À'   => 'a', 'Á'   => 'a', 'Ả'   => 'a', 'Ã'   => 'a', 'Ạ'   => 'a',
            'Ă'   => 'a', 'Ằ'   => 'a', 'Ắ'   => 'a', 'Ẳ'   => 'a', 'Ẵ'   => 'a', 'Ặ'   => 'a',
            'Â'   => 'a', 'Ầ'   => 'a', 'Ấ'   => 'a', 'Ẩ'   => 'a', 'Ẫ'   => 'a', 'Ậ'   => 'a',
            'đ'   => 'd', 'Đ'   => 'd',
            'è'   => 'e', 'é'   => 'e', 'ẻ'   => 'e', 'ẽ'   => 'e', 'ẹ'   => 'e',
            'ê'   => 'e', 'ề'   => 'e', 'ế'   => 'e', 'ể'   => 'e', 'ễ'   => 'e', 'ệ'   => 'e',
            'È'   => 'e', 'É'   => 'e', 'Ẻ'   => 'e', 'Ẽ'   => 'e', 'Ẹ'   => 'e',
            'Ê'   => 'e', 'Ề'   => 'e', 'Ế'   => 'e', 'Ể'   => 'e', 'Ễ'   => 'e', 'Ệ'   => 'e',
            'ì'   => 'i', 'í'   => 'i', 'ỉ'   => 'i', 'ĩ'   => 'i', 'ị'   => 'i',
            'Ì'   => 'i', 'Í'   => 'i', 'Ỉ'   => 'i', 'Ĩ'   => 'i', 'Ị'   => 'i',
            'ò'   => 'o', 'ó'   => 'o', 'ỏ'   => 'o', 'õ'   => 'o', 'ọ'   => 'o',
            'ô'   => 'o', 'ồ'   => 'o', 'ố'   => 'o', 'ổ'   => 'o', 'ỗ'   => 'o', 'ộ'   => 'o',
            'ơ'   => 'o', 'ờ'   => 'o', 'ớ'   => 'o', 'ở'   => 'o', 'ỡ'   => 'o', 'ợ'   => 'o',
            'Ò'   => 'o', 'Ó'   => 'o', 'Ỏ'   => 'o', 'Õ'   => 'o', 'Ọ'   => 'o',
            'Ô'   => 'o', 'Ồ'   => 'o', 'Ố'   => 'o', 'Ổ'   => 'o', 'Ỗ'   => 'o', 'Ộ'   => 'o',
            'Ơ'   => 'o', 'Ờ'   => 'o', 'Ớ'   => 'o', 'Ở'   => 'o', 'Ỡ'   => 'o', 'Ợ'   => 'o',
            'ù'   => 'u', 'ú'   => 'u', 'ủ'   => 'u', 'ũ'   => 'u', 'ụ'   => 'u',
            'ư'   => 'u', 'ừ'   => 'u', 'ứ'   => 'u', 'ử'   => 'u', 'ữ'   => 'u', 'ự'   => 'u',
            'Ù'   => 'u', 'Ú'   => 'u', 'Ủ'   => 'u', 'Ũ'   => 'u', 'Ụ'   => 'u',
            'Ư'   => 'u', 'Ừ'   => 'u', 'Ứ'   => 'u', 'Ử'   => 'u', 'Ữ'   => 'u', 'Ự'   => 'u',
            'ỳ'   => 'y', 'ý'   => 'y', 'ỷ'   => 'y', 'ỹ'   => 'y', 'ỵ'   => 'y',
            'Y'   => 'y', 'Ỳ'   => 'y', 'Ý'   => 'y', 'Ỷ'   => 'y', 'Ỹ'   => 'y', 'Ỵ'   => 'y',
            ' - ' => '', ' '   => ''
        );

        $str = strtolower(strtr($string, $trans));
        $str = preg_replace('/[^a-zA-Z0-9\s\-]/', '', $str);
        $str = ltrim($str, '-');
        $str = rtrim($str, '-');
        return $str;
    }

}

/**
 * End of Utils
 */
